package interface1;

import java.awt.BorderLayout;
import java.awt.Container;
import java.sql.*;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import back_database.DBAccess;


public class Result{
	
	private static final long serialVersionUID = 1L;
	private Connection connection;
	private Statement statement;
	private ResultSet resultSet;
	private ResultSetMetaData rsMetaData;
	
	public Result(){
		
		
	}
	
	// 完成传入sql语句， 返回表的Data行结果集
	public Vector getTable(String query)
	{
		connection = new DBAccess().getConnection();
		Vector vec = new Vector();
		try {
			statement = connection.createStatement();
			resultSet = statement.executeQuery(query);  // executeQuery
			vec = displayResultSet(resultSet);// 在表格中 显示查询结果
			
		}
		catch(SQLException sqlex) {
			sqlex.printStackTrace();
		}
		return vec;
	}

	public Vector displayResultSet(ResultSet rs) throws SQLException{
		   
		   boolean flag= rs.isBeforeFirst() && rs.isAfterLast();
		   if(flag){
			   JOptionPane.showMessageDialog(null, this, "结果集中没有记录", 0);
			   return null;
		   }
		   
		   Vector columnHeads=new Vector();
		   Vector rows=new Vector();
		   ResultSetMetaData meta=rs.getMetaData();
			int count = meta.getColumnCount();// 字段个数
			for(int k=1;k<=count;k++){
				columnHeads.addElement(meta.getColumnName(k));
			}
			
			while (rs.next()) {
				Vector v=new Vector();
				for (int k = 1; k <= count; k++) {
					v.addElement(rs.getString(k));				
				}
				rows.add(v);
			}
			
			return rows;
	   }


	private Object getNextRow(ResultSet rs, ResultSetMetaData rsmd) throws SQLException{
		
		Vector currentRow = new Vector();
		for(int i = 1 ; i<= rsmd.getColumnCount(); i++)
			currentRow.addElement(rs.getString(i));
		
		return currentRow;
	}
	
	public void shutDown(Connection connection)
	{
		try {
			// 断开数据库连接
			connection.close();
		}
		catch( SQLException sqlex)
		{
			System.out.println("Unable to disconnect");
			sqlex.printStackTrace();
		}
	}

	public ResultSetMetaData getRsMetaData(String query) {
		connection = new DBAccess().getConnection();
		
		try {
			statement = connection.createStatement();
			resultSet = statement.executeQuery(query);  // executeQuery
			ResultSetMetaData meta=resultSet.getMetaData();
		    this.rsMetaData = meta;
		}
		catch(SQLException sqlex) {
			sqlex.printStackTrace();
		}
		return rsMetaData;
	}

	
}